package com.wanli.storemobile.homepage;


import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.wanli.storemobile.R;
import com.wanli.storemobile.base.BaseActivity;
import com.wanli.storemobile.base.DataCallBack;
import com.wanli.storemobile.bean.BaseResponseBean;
import com.wanli.storemobile.bean.ImageBean;
import com.wanli.storemobile.dialog.ChooseIndustryDialog;
import com.wanli.storemobile.event.NewAddStoreEvent;
import com.wanli.storemobile.homepage.model.HomePageModelImpl;
import com.wanli.storemobile.homepage.model.IHomePageModel;
import com.wanli.storemobile.utils.Base64BitmapUtil;
import com.wanli.storemobile.utils.GlideEngine;
import com.wanli.storemobile.utils.GlideUtils;
import com.wanli.storemobile.utils.PermissionsManager;
import com.wanli.storemobile.utils.ToastUtil;
import com.wanli.storemobile.widget.AppTitleBar;
import com.wanli.storemobile.widget.ViewLoading;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NewAddStoreActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.edit_store_name)
    EditText editStoreName;
    @BindView(R.id.ic_prcture_1)
    ImageView icPrcture1;
    @BindView(R.id.iv_picture_demo_1)
    ImageView ivPictureDemo1;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.tv_industry_type)
    TextView tvIndustryType;
    @BindView(R.id.ll_industry_layout)
    LinearLayout llIndustryLayout;
    private String prctureDemo1 = "https://wnb-dc.oss-cn-qingdao.aliyuncs.com/resources/73aa7ade644dce8bc6d103fc08480f5.jpg";
    private BottomSheetDialog selectPicDialog;
    private PermissionsManager permissionsManager;
    private String[] permissions;
    private int openType;//0 相册，1相机
    private List<LocalMedia> mediaList = new ArrayList<>();
    private IHomePageModel homePageModel = new HomePageModelImpl();
    private String imgPath1;
    private String mcc_code = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_add_store);
        ButterKnife.bind(this);
        initView();
    }

    public void initView() {
        permissionsManager = new PermissionsManager(NewAddStoreActivity.this);
        GlideUtils.loadImage(mActivity, ivPictureDemo1, prctureDemo1);
    }

    @OnClick({R.id.ic_prcture_1, R.id.ll_industry_layout, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ic_prcture_1:
                showPictureSelectorDialog();
                break;
            case R.id.tv_commit:
                commit();
                break;
            case R.id.ll_industry_layout:
                ChooseIndustryDialog dialog1 = ChooseIndustryDialog.newInstance("1");
                dialog1.show(getSupportFragmentManager(), "dialog");
                dialog1.setOnCallBackListener((name, code) -> {
                    tvIndustryType.setText("(" + code + ")" + name);
                    mcc_code = code;
                });
                break;
        }
    }

    public void commit() {
        String name = editStoreName.getText().toString();
        if (TextUtils.isEmpty(name)) {
            ToastUtil.showShort("请输入门店名称");
            return;
        }
        if (TextUtils.isEmpty(mcc_code)) {
            ToastUtil.showShort("请选择行业类型");
            return;
        }
        if (TextUtils.isEmpty(imgPath1)) {
            ToastUtil.showShort("请上传门店门头照");
            return;
        }
        ViewLoading.showProgress(mActivity, "提交中......");
        homePageModel.requestIncomeToQuickSub(name, mcc_code, imgPath1, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort(bean.getMsg());
                EventBus.getDefault().post(new NewAddStoreEvent());
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> mediaList = PictureSelector.obtainMultipleResult(data);
                    if (mediaList.size() > 0) {
                        String imgPath = mediaList.get(0).getCompressPath();
                        requestUploadFile(imgPath);
                    }
                    break;
            }
        }

    }

    /**
     * 上传图片
     */
    public void requestUploadFile(String imgPath) {
        ViewLoading.showProgress(mActivity, "上传中......");
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        String file = Base64BitmapUtil.bitmapToBase64(bitmap);
        homePageModel.requestUploadFile("store", file, new DataCallBack<ImageBean>() {
            @Override
            public void onSuccessful(ImageBean bean) {
                ToastUtil.showShort("上传成功");
                imgPath1 = bean.getData();
                GlideUtils.loadImage(mActivity, icPrcture1, imgPath);
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private void showPictureSelectorDialog() {

        selectPicDialog = new BottomSheetDialog(mActivity, R.style.Dialog);
        selectPicDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_bottom_select_pictrue, null);
        // 相册
        TextView album = view.findViewById(R.id.tv_select_pictrue_album);
        // 相机
        TextView camera = view.findViewById(R.id.tv_select_pictrue_camera);
        // 取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);

        album.setOnClickListener(v -> handlerPhotoAlbumClick());
        camera.setOnClickListener(v -> handlerCameraClick());
        cancel.setOnClickListener(v -> cancelPictureDialog());

        selectPicDialog.setContentView(view);
        selectPicDialog.show();
    }

    /**
     * 点击相机
     */
    private void handlerCameraClick() {
        openType = 1;
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.CAMERA};

        if (PermissionsManager.checkPermissions(permissions)) {
            openCamera();
            cancelPictureDialog();
            return;
        }

        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openCamera();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 点击相册
     */
    private void handlerPhotoAlbumClick() {
        openType = 0;
        cancelPictureDialog();
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.READ_EXTERNAL_STORAGE};

        if (PermissionsManager.checkPermissions(permissions)) {
            openPhotoAlbum();
            cancelPictureDialog();
            return;
        }
        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        PictureSelector.create(NewAddStoreActivity.this)
                .openCamera(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
        cancelPictureDialog();

    }

    /**
     * 打开相册
     */
    private void openPhotoAlbum() {
        PictureSelector.create(NewAddStoreActivity.this)//
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于20kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void cancelPictureDialog() {
        if (selectPicDialog != null) {
            selectPicDialog.cancel();
        }
    }

    @Override
    public void handlerPermissionForActivityResult() {
        if (PermissionsManager.checkPermissions(permissions)) {
            if (openType == 0) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else if (openType == 1) {
                openCamera();
                cancelPictureDialog();
            }
        }
    }
}
